package com.paipai.service;


import java.util.HashMap;
import java.util.Map;
import java.net.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.paipai.utils.AuthCodeUtils;

@Service
public class AuthCodeServlet  {
	//聚合数据连接数据
	private static final String URLSITE = "http://v.juhe.cn/sms/send";
	//短信模板
	private static final String NOTETEMPLAE = "201043";
	
	private static final String KEY = "e33f5cf779b0e3f6764133c892f8695c";
	
	@Autowired
	private RedisTemplate<String, String> rt;
	
	

	/**
	 * 发送验证码
	 * 
	 * @param rphone
	 * @return
	 */
	//@Override
	public Boolean AuthCodeVerify(String rphone) {
		
		String result =null;
		Map <String,String> params = new HashMap<String,String>();// 请求参数

		//随机验证码
		String random = AuthCodeUtils.getRandom();
		
		params.put("mobile", rphone);// 接受手机号码
		params.put("tpl_id", NOTETEMPLAE);// 短信模板ID，请参考个人中心短信模板设置
		params.put("tpl_value", "#code#="+random+"&#m#=5");
		params.put("key", KEY);// 应用APPKEY(应用详细页查询)
		params.put("dtype", "json");// 返回数据的格式,xml或json，默认json
		
		//
		try {
			URL url = new URL("http://www.runoob.com");
			result =AuthCodeUtils.net(URLSITE, params, "GET");
			//从返回的json格式字符串得到一个json操作对象
			JSONObject parseObject = JSON.parseObject(result);
			//短信发送成功
			if(parseObject.getInteger("error_code")==0) {
				//获得一个redis操作对象
				ValueOperations<String, String> opValue = rt.opsForValue();
				opValue.set(rphone, random, 1000*300);
				
				return true;
			//发送失败
			}else {
				 return false;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(result);
		return false;
	}


	/**
	 * 检查验证码
	 */
	//@Override
	public Boolean authCodeVerify(String authCode,String phone) {
		//获得一个redis操作对象
		ValueOperations<String, String> opValue = rt.opsForValue();
		//根据号码获取验证码
		String authCodeStr = opValue.get(phone);
		System.out.println(authCodeStr);
		System.out.println(authCode);
		
		//
		//如果redis验证码等于null 返回false 如果跟redis验证码不符合页返回false
		if(authCodeStr==null||!authCode.equals(authCodeStr.trim())) return false;
		
		//相等则返回true
		return true;
	}

	

   

  

	
	
}
